package com.stutterweb.server;

import com.stutterweb.client.GreetingService;
import com.stutterweb.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 10 characters long");
		}

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);

		return findStutter(input);
	}

	private String findStutter(String input) {
		String line_delimiter = "[\r\n]";
		String[] line = input.split(line_delimiter);
		String lastWord = new String();
		String results = new String();
		
		for (int j = 0; j < line.length; j++) {
			String word_delimiter = "[ .,!?:;(\"-]";
			String[] words = line[j].split(word_delimiter);
			
			for (int i = 0; i < words.length; i++) {
				
				if (!lastWord.isEmpty())
					if (compareWords(lastWord, words[i])) {
						results = results +  "Repeated word on line " + (j+1) + " " + lastWord + " " + words[i] + "<br />";
						lastWord = new String();
					}
				
				if (i+1 > words.length - 1) {
					lastWord = words[i];
					break;
				}
				
				if (compareWords(words[i], words[i+1]))
					results = results +  "Repeated word on line " + (j+1) + " " + words[i] + " " + words[i+1] + "<br />";
						
			}
		}
		
		return results;
	}
	
	/**
	 * Compare _word1 to _word2
	 * 
	 * @param _word1
	 * @param _word2
	 * @return true if equal
	 */
	private boolean compareWords(String _word1, String _word2) {
		return (_word1.equals(_word2) ? true : false);
	}	

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
